package dao;

import pojo.User;
import utils.JDBCUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class UserDAO {

    private static final String TABLE_NAME = "tb_users";

    // 删除用户
    public static void deleteUser(int id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        JDBCUtils.execute(sql, id);
    }

    // 更新用户信息
    public static void updateUser(User user) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET username = ?, nickname = ?, avatar = ?, remember_me_token = ?, role_type = ?, updated_at = ? WHERE id = ?";
        JDBCUtils.execute(sql, user.getUsername(), user.getNickname(), user.getAvatar(),
                user.getRememberMeToken(), user.getRoleType(), user.getUpdatedAt(), user.getId());
    }

    // 检查用户名是否存在
    public static boolean usernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) AS count FROM " + TABLE_NAME + " WHERE username = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, username);
        if (resultSet.next()) {
            return resultSet.getInt("count") > 0;
        }
        return false;
    }

    // 校验旧密码
    public static boolean checkOldPassword(String username, String oldPassword) throws SQLException {
        String sql = "SELECT COUNT(*) AS count FROM " + TABLE_NAME + " WHERE username = ? AND password = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, username, oldPassword);
        if (resultSet.next()) {
            return resultSet.getInt("count") > 0;
        }
        return false;
    }

    // 注册用户
    public static void register(User user) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (username, password, nickname, avatar, remember_me_token, role_type, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql, user.getUsername(), user.getPassword(), user.getNickname(), user.getAvatar(),
                user.getRememberMeToken(), user.getRoleType(), user.getCreatedAt(), user.getUpdatedAt());
    }

    // 用户登录，更新rememberMe token，并返回用户信息
    public static User login(String username, String password, HttpServletRequest request, HttpServletResponse response) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE username = ? AND password = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, username, password);
        if (resultSet.next()) {
            User user = createUserFromResultSet(resultSet);

            // 生成新的 rememberMe token
            String rememberMeToken = UUID.randomUUID().toString().replace("-", "");
            user.setRememberMeToken(rememberMeToken);

            // 更新数据库中的 rememberMe token
            updateRememberMeToken(user.getId(), rememberMeToken);

            // 从请求中获取 rememberMe 参数
            String rememberMeParam = request.getParameter("rememberMe");
            boolean rememberMe = rememberMeParam != null && rememberMeParam.equals("on");

            if (rememberMe) {
                // 设置 Cookie 发送给客户端
                Cookie cookie = new Cookie("rememberMe", rememberMeToken);
                cookie.setMaxAge(60 * 60); // 设置有效期为1h
                cookie.setPath("/"); // 设置 Cookie 的作用路径
                response.addCookie(cookie);
            }

            return user;
        }
        return null;
    }


    // 更新 rememberMe token
    private static void updateRememberMeToken(int userId, String token) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET remember_me_token = ? WHERE id = ?";
        JDBCUtils.execute(sql, token, userId);
    }

    // 修改密码，并清除 rememberMe token
    public static void changePassword(String username, String newPassword) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET password = ?, remember_me_token = NULL WHERE username = ?";
        JDBCUtils.execute(sql, newPassword, username);
    }

    // 忘记密码，重置为默认密码000000
    public static void resetPassword(String username) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?";
        JDBCUtils.execute(sql, "000000", username);
    }


    // 获取所有用户
    public static List<User> getAll() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            User user = createUserFromResultSet(resultSet);
            users.add(user);
        }
        return users;
    }

    // 获取用户数量
    public static int getCount() throws SQLException {
        String sql = "SELECT COUNT(*) AS count FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        if (resultSet.next()) {
            return resultSet.getInt("count");
        }
        return 0;
    }

    // 根据关键字分页模糊查询用户
    public static List<User> findByKeyword(String keyword, int page, int pageSize) throws SQLException {
        List<User> users = new ArrayList<>();
        int start = (page - 1) * pageSize; // 计算偏移量
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE username LIKE ? OR nickname LIKE ? LIMIT ?, ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, "%" + keyword + "%", "%" + keyword + "%", start, pageSize);
        while (resultSet.next()) {
            User user = createUserFromResultSet(resultSet);
            users.add(user);
        }
        return users;
    }

    // 获取根据关键字模糊查询匹配到的记录数
    public static int getCountByKeyword(String keyword) throws SQLException {
        String sql = "SELECT COUNT(*) AS count FROM " + TABLE_NAME + " WHERE username LIKE ? OR nickname LIKE ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, "%" + keyword + "%", "%" + keyword + "%");
        if (resultSet.next()) {
            return resultSet.getInt("count");
        }
        return 0;
    }

    // 创建User对象从ResultSet
    private static User createUserFromResultSet(ResultSet resultSet) throws SQLException {
        int id = resultSet.getInt("id");
        String username = resultSet.getString("username");
        String password = resultSet.getString("password");
        String nickname = resultSet.getString("nickname");
        String avatar = resultSet.getString("avatar");
        String rememberMeToken = resultSet.getString("remember_me_token");
        String roleType = resultSet.getString("role_type");
        LocalDateTime created_at = resultSet.getTimestamp("created_at").toLocalDateTime();
        LocalDateTime updated_at = resultSet.getTimestamp("updated_at").toLocalDateTime();
        // 使用LocalDateTime解析时间
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setRememberMeToken(rememberMeToken);
        user.setRoleType(roleType);
        user.setCreatedAt(created_at);
        user.setUpdatedAt(updated_at);
        return user;
    }

    // 根据 rememberMe token 获取用户
    public static User getUserByRememberMeToken(String token) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE remember_me_token = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, token);
        if (resultSet.next()) {
            return createUserFromResultSet(resultSet);
        }
        return null;
    }
}
